package com.bjy.qa.controller.functionaltest;

import com.bjy.qa.entity.Response;
import com.bjy.qa.entity.functionaltest.*;
import com.bjy.qa.entity.tools.Task;
import com.bjy.qa.enumtype.FileType;
import com.bjy.qa.service.functionaltest.IApiService;
import com.bjy.qa.service.tools.ITaskManagerService;
import com.bjy.qa.util.EnumUtil;
import com.bjy.qa.util.security.SecurityUtils;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/ft/api")
@Validated
@io.swagger.annotations.Api(tags = "API 定义")
public class ApiController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    IApiService iApiService;

    @Resource
    ITaskManagerService iTaskManagerService;

    @RequestMapping(value = "/selectAll", method = {RequestMethod.POST})
    @ResponseBody
    @ApiOperation(value = "返回所有 api 定义列表", notes = "返回所有 api 定义列表")
    public Response<List<Api>> selectAll(@RequestBody Api api) {
        logger.info("返回所有 api 定义列表，{}", api);
        Response response = Response.success(iApiService.selectAll());
        logger.info("{}", response);
        return response;
    }

    @RequestMapping(value = "/add", method = {RequestMethod.POST})
    @ResponseBody
    @ApiOperation(value = "添加 api 定义信息", notes = "添加 api 定义信息")
    public Response<Integer> add(@RequestBody @Valid Api api) throws Exception {
        logger.info("添加 api 定义信息，{}", api);
        Response response = Response.success(iApiService.add(api, SecurityUtils.getCurrentUserName()));
        logger.info("{}", response);
        return response;
    }

    @RequestMapping(value = "/selectById", method = {RequestMethod.GET})
    @ResponseBody
    @ApiOperation(value = "查询 api 定义信息", notes = "查询 api 定义信息")
    public Response<Api> selectById(@NotNull(message = "type: type字段必填") Integer type, @NotNull(message = "ID: id字段必填") Long id) {
        logger.info("查询 api 定义信息，type: {}, id: {}", type, id);
        Response response = Response.success(iApiService.selectById(type, id));
        logger.info("{}", response);
        return response;
    }

    @RequestMapping(value = "/update", method = {RequestMethod.POST})
    @ResponseBody
    @ApiOperation(value = "修改 api 定义信息", notes = "修改 api 定义信息")
    public Response<Integer> update(@RequestBody @Valid Api api) throws Exception {
        logger.info("修改 api 定义信息，{}", api);
        Response response = Response.success(iApiService.update(api, SecurityUtils.getCurrentUserName()));
        logger.info("{}", response);
        return response;
    }

    @RequestMapping(value = "/delete", method = {RequestMethod.GET})
    @ResponseBody
    @ApiOperation(value = "删除 api 定义信息", notes = "删除 api 定义信息")
    public Response<Integer> delete(@NotNull(message = "ID: id字段必填") Long id) {
        logger.info("删除 api 定义信息，ID：" + id);
        Response response = Response.success(iApiService.delete(id));
        logger.info("{}", response);
        return response;
    }

    @RequestMapping(value = "/search", method = {RequestMethod.POST})
    @ResponseBody
    @ApiOperation(value = "搜索 api 定义信息", notes = "搜索 api 定义信息")
    public Response<List<Api>> search(@RequestBody @Valid SearchDTO searchDTO) {
        logger.info("搜索 api 定义信息，{}", searchDTO);
        Response response = Response.success(iApiService.search(searchDTO));
        logger.info("搜索 api 定义信息，成功 {}", response);
        return response;
    }

    @ApiOperation(value = "导入接口定义", notes = "导入接口定义")
    @ResponseBody
    @RequestMapping(value = "/apiFileImport", method = {RequestMethod.GET})
    public Response<Object> apiFileImport(@NotNull(message = "fileType: fileType字段必填") String fileType, @NotNull(message = "filePath: filePath字段必填") String filePath, @NotNull(message = "projectId: projectId字段必填") Long projectId) {
        logger.info("导入接口定义，fileType:{}， filePath：{}， projectId:{}", fileType, filePath, projectId);
        Task task = iTaskManagerService.newTask(); // 创建任务

        Map<String, String> map = new HashMap<>();
        map.put("taskId", task.getTaskId());
        map.put("filePath", filePath);
        iApiService.apiFileImport(task.getTaskId(), EnumUtil.valueOf(FileType.class, Integer.valueOf(fileType).intValue()), filePath, projectId, SecurityUtils.getCurrentUserName()); // 异步导入测试用哦
        Response response = Response.successAsync(map);

        logger.info("导入接口定义，成功。{}", response);
        return response;
    }

    @ApiOperation(value = "cURL 导入接口定义", notes = "cURL 导入接口定义")
    @ResponseBody
    @RequestMapping(value = "/apiCurlImport", method = {RequestMethod.POST})
    public Response<Object> apiFileImport(@RequestBody @Valid CurlImportDTO curlImportDTO) {
        logger.info("cURL 导入接口定义 {}", curlImportDTO);
        Response response = Response.success(iApiService.apiCurlImport(curlImportDTO));
        logger.info("cURL 导入接口定义，成功。{}", response);
        return response;
    }

    @ApiOperation(value = "API 导出", notes = "API 导出")
    @ResponseBody
    @RequestMapping(value = "/apiExport", method = {RequestMethod.POST})
    public Response<Object> apiExport(@RequestBody Map<String,Object> params) {
        logger.info("API 导出 type: {}, id: {}", params.get("type"), params.get("id"));
        Response response = Response.success(iApiService.apiExport(Integer.valueOf(params.get("type").toString()), Long.valueOf(params.get("id").toString())));
        logger.info("API 导出，成功。{}", response);
        return response;
    }

    @ApiOperation(value = "发送 Api 调试请求", notes = "发送 Api 调试请求")
    @ResponseBody
    @RequestMapping(value = "/apiDebug", method = {RequestMethod.POST})
    public Response<Object> apiDebug(@RequestBody @Valid ApiDebugDTO apiDebugDTO) {
        logger.info("发送 Api 调试请求，{}", apiDebugDTO);
        Response response = Response.success(iApiService.apiDebug(apiDebugDTO));
        logger.info("发送 Api 调试请求，成功 {}", response);
        return response;
    }

    @ApiOperation(value = "获取 Api 调试 结果", notes = "获取 Api 调试 结果")
    @ResponseBody
    @RequestMapping(value = "/getApiDebugStatus", method = {RequestMethod.GET})
    public Response<ApiLogDTO> getApiDebugStatus(@NotNull(message = "sessionId: sessionId 字段必填") String sessionId, @NotNull(message = "timestamp: timestamp 字段必填") Long timestamp) {
        logger.info("获取 Api 调试 结果，sessionId:{}, timestamp:{}", sessionId, timestamp);
        Response response = Response.success(iApiService.getApiDebugStatus(sessionId, timestamp));
        logger.info("获取 Api 调试 结果，成功 {}", response);
        return response;
    }
}
